package com.itcrx.emalladmin.controller;

import com.itcrx.emalladmin.model.dto.UsersLoginDTO;
import com.itcrx.emalladmin.model.entity.Users;
import com.itcrx.emalladmin.model.result.Result;
import com.itcrx.emalladmin.model.vo.UsersLoginVO;
import com.itcrx.emalladmin.properties.JwtProperties;
import com.itcrx.emalladmin.service.IUsersService;
import com.itcrx.emalladmin.utils.JwtUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author NoobMaster69  * @date 2024/6/5 0005 星期三 9:05
 */
@RestController
@Tag(name = "用户相关接口")
@Slf4j
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService iUsersService;

    @Autowired
    private JwtProperties jwtProperties;
    @PostMapping("/login")
    @Schema(name = "用户登录")
    public Result<UsersLoginVO> login(@RequestBody UsersLoginDTO usersLoginDTO){
        log.info("用户登录：{}",usersLoginDTO);

        Users users = iUsersService.login(usersLoginDTO);

        //登录成功后创建jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId",users.getUsersId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UsersLoginVO usersLoginVO = UsersLoginVO.builder()
                .usersId(users.getUsersId())
                .userLogin(users.getUserLogin())
                .userNickName(users.getUserNikeName())
                .token(token)
                .build();


        return Result.success(usersLoginVO);
    }

}
